const wx = require('./common');
// 添加客服
async function add(data){
	let access_token=await wx.getToken()
	let addUrl =
		`https://api.weixin.qq.com/customservice/kfaccount/add?access_token=${access_token}`
	let addRes = await uniCloud.httpclient.request(addUrl, {
		method: 'POST',
		data: JSON.stringify(data),
		dataType: 'json'
	})
	console.log(addRes)
	if(addRes.data.errcode===0&&addRes.data.errmsg==='ok'){
		return {
			data:'success',
			status:200
		}
	}else{
		return {
			msg:'服务器出错',
			data:false,
			status:400
		}
	}
}
// 修改客服信息
async function edit(data) {
	let data=params.data
	let access_token=await wx.getToken()
	let updateUrl =
		`https://api.weixin.qq.com/customservice/kfaccount/update?access_token=${access_token}`
	let updateRes = await uniCloud.httpclient.request(updateUrl, {
		method: 'POST',
		data: data,
		dataType: 'json'
	})
	console.log(updateRes)
	if(updateRes.data.errcode===0&&updateRes.data.errmsg==='ok'){
		return {
			data:'success',
			status:200
		}
	}else{
		return {
			msg:'服务器出错',
			data:false,
			status:400
		}
	}
}
// 删除客服账号
async function deleted(data) {
	let access_token=await wx.getToken()
	let delUrl =
		`https://api.weixin.qq.com/customservice/kfaccount/del?access_token=${access_token}`
	let delRes = await uniCloud.httpclient.request(delUrl, {
		method: 'POST',
		data: data,
		dataType: 'json'
	})
	if(delRes.data.errcode===0&&delRes.data.errmsg==='ok'){
		return {
			data:'success',
			status:200
		}
	}else{
		return {
			msg:'服务器出错',
			data:false,
			status:400
		}
	}
}
// 设置客服头像
async function setAvatar(params) {
	
}
// 获取客服账号列表
async function getList(data) {
	let access_token=await wx.getToken()
	let listUrl =
		`https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=${access_token}`
	let listRes = await uniCloud.httpclient.request(listUrl, {
		method: 'GET',
		data: {},
		dataType: 'json'
	})
	console.log(listRes)
	if(listRes.data.errcode===0&&listRes.data.errmsg==='ok'){
		return {
			data:listRes.data,
			status:200
		}
	}else{
		return {
			msg:'服务器出错',
			data:false,
			status:400
		}
	}
}
// 发送客服消息
async function sendMsg(params) {
	if(!params||!params.data||params.options!=='send'){
		return {
			msg:'非法访问',
			data:false,
			status:400
		}
	}
	// 组织发送消息的格式
	let data={}
	let access_token=await wx.getToken()
	let sendUrl =
		`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${access_token}`
	let sendRes = await uniCloud.httpclient.request(sendUrl, {
		method: 'POST',
		data: data,
		dataType: 'json'
	})
	if(sendRes.data.errcode===0&&sendRes.data.errmsg==='ok'){
		return {
			data:'success',
			status:200
		}
	}else{
		return {
			msg:'服务器出错',
			data:false,
			status:400
		}
	}
}

module.exports = {
	add,
	edit,
	deleted,
	setAvatar,
	getList,
	sendMsg
}
